package org.nuonuo.sdk.client;

/**
 * @Version 1.0
 * @Author az
 * @Date 2024-03-28 11:03:16
 * @ClassName ModuleSign
 * @Description
 */

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

final class ModuleSign {
    ModuleSign() {
    }

    static String getSign(String path, String secret, String appKey, String senid, String nonce, String body, String timestamp) {
        String[] split = path.split("/");
        StringBuffer signStr = new StringBuffer();
        signStr.append("a=" + split[3]).append("&l=" + split[2]).append("&p=" + split[1]).append("&k=" + appKey).append("&i=" + senid).append("&n=" + nonce).append("&t=" + timestamp).append("&f=" + body);
        return hmacSha1WithBase64(signStr.toString(), secret);
    }

    private static String hmacSha1WithBase64(String value, String key) {
        try {
            byte[] rawHmac = hmacSha1(value, key);
            byte[] base64Result = Base64.encodeBase64(rawHmac);
            return new String(base64Result, "UTF-8");
        } catch (Exception var4) {
            throw new RuntimeException(var4);
        }
    }

    private static byte[] hmacSha1(String value, String key) {
        try {
            byte[] keyBytes = key.getBytes();
            SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);
            return mac.doFinal(value.getBytes("utf-8"));
        } catch (Exception var5) {
            throw new RuntimeException(var5);
        }
    }
}